<?php
namespace app\beautiful\middleware;
use app\beautiful\model\StaffModel;
use app\common\logic\TokenLogic;
use app\common\model\AppModel;
use app\common\model\ShopModel;

class CashierCheck{
    use \app\BaseTrait;
    /**
     * 处理请求
     *  验证是否登录是否正确的中间件
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        $auth_token = $request->param('cashiser_auth_token');
        if(empty($auth_token)){
            return $this->error('未登录',100);
        }
        //验证token
        $res = TokenLogic::getStaffInfo($auth_token);
        if(false == $res){
            return $this->error('未登录',100);
        }

        $request->staffId=$res;

        //判断员工存不存在
        if(null === $staff = StaffModel::where([
                ['staff_id','=',$res],
                ['status','=',1],
                ['is_delete','=',0]
            ])->find()){
            return $this->error('员工不存在',100);
        }

        $request->staff=$staff;


        //验证商铺
        if(null === $shop = ShopModel::find($staff->shop_id)){
            return $this->error('商铺不存在',102);
        }
        if($shop->expire_time<$request->time()){
            return $this->error('商铺已过期',100);
        }
        $request->shopId=$shop->shop_id;
        $request->shop=$shop;

        //验证应用
        if(null == $app = AppModel::find($shop->app_id)){
            return $this->error('应用不存在',100);
        }

        //开发完成之后再取消注释
//        if($app->status==0){
//            return $this->error('应用还在开发中',100);
//        }

        if($app->iden!='beautiful'){
            return $this->error('应用错误',100);
        }

        $request->appId=$app->app_id;

        return $next($request);
    }
}